package com.shadow.baiqun.delegate.receive.upload;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.Group;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.baiqun.event.RefreshWaitPutEvent;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.callback.file.UpLoadCallback;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;
import com.shadow.ui.camera.Glide4Engine;
import com.shadow.ui.progress.sweetalert.DialogLoader;
import com.shadow.ui.progress.sweetalert.IDialogClickListener;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class UploadFileDelegate extends RxShadowDelegate {
    private static final int REQUEST_CODE_CHOOSE = 100;
    private static final String ORDER_ID = "orderId";
    private static final RequestOptions REQUEST_OPTIONS =
            new RequestOptions().centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .dontAnimate();

    public static UploadFileDelegate create(int orderId) {
        final UploadFileDelegate contentDelegate = new UploadFileDelegate();
        final Bundle bundle = new Bundle();
        bundle.putInt(ORDER_ID, orderId);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.group)
    Group mGroup;
    @BindView(R2.id.btn_choose_image)
    Button mButtonChoose;
    @BindView(R2.id.iv_image)
    ImageView mImageView;
    List<String> mSelected;
    private int mOrderId;
    private ProgressDialog mProgressDialog;
    private DialogLoader mDialogLoader;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            UploadFileDelegatePermissionsDispatcher.getMultiWithCheck(this);
        }
        Bundle bundle = getArguments();
        if (bundle != null) {
            mOrderId = bundle.getInt(ORDER_ID);
        }
    }

    @NeedsPermission({Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA
            , Manifest.permission.MEDIA_CONTENT_CONTROL})
    public void getMulti() {
        Toast.makeText(getContext(), "getMulti", Toast.LENGTH_SHORT).show();
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_upload_file;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("上传送货单");
        }
        initProgress(getContext());
        mDialogLoader = new DialogLoader(getContext());
    }

    @OnClick(R2.id.btn_choose_image)
    public void onChooseImage() {
        Set<MimeType> set = new HashSet<>();
        set.add(MimeType.JPEG);
        Matisse.from(this)
                .choose(set, false)
                .countable(true)
                .capture(true)
                .showSingleMediaType(true)
                .captureStrategy(
                        new CaptureStrategy(true, "com.logistics.baiqun.fileprovider"))
                .maxSelectable(1)
                .gridExpectedSize(
                        getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new Glide4Engine())
                .originalEnable(true)
                .maxOriginalSize(10)
                .forResult(REQUEST_CODE_CHOOSE);
    }

    @OnClick(R2.id.iv_delete)
    public void onDelete() {
        mGroup.setVisibility(View.GONE);
        mButtonChoose.setVisibility(View.VISIBLE);
        if (mSelected != null) {
            mSelected.clear();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> list = Matisse.obtainResult(data);
            mSelected = Matisse.obtainPathResult(data);
            Log.e("OnActivityResult ", mSelected.get(0));
            if (mSelected != null && !mSelected.isEmpty()) {
                mGroup.setVisibility(View.VISIBLE);
                mButtonChoose.setVisibility(View.GONE);
                Glide.with(getContext())
                        .load(list.get(0))
                        .apply(REQUEST_OPTIONS)
                        .into(mImageView);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        UploadFileDelegatePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnClick(R2.id.btn_upload)
    public void onUpload() {
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/collectgoods/upPgoodsImg")
                .params("pgid", mOrderId)
                .file(new File(mSelected.get(0)))
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        dismissProgressDialog();
                        ResultConverter resultConverter = new ResultConverter();
                        int code = resultConverter.getCode(response);
                        if (code == 1) {
                            mDialogLoader.showSuccess("恭喜", "图片上传成功!", new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.clearDialog();
                                    pop();
                                    EventBus.getDefault().post(new RefreshWaitPutEvent());
                                }
                            });
                        } else if (code == 2) {
                            mDialogLoader.showFailed("图片上传失败", "该工单不能上传图片", new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.clearDialog();
                                    pop();
                                    EventBus.getDefault().post(new RefreshWaitPutEvent());
                                }
                            });
                        }

                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        dismissProgressDialog();
//                        ToastUtils.showToast(getContext(), msg);
                        mDialogLoader.showSuccess("恭喜", "图片上传成功!", new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.clearDialog();
                                pop();
                                EventBus.getDefault().post(new RefreshWaitPutEvent());
                            }
                        });
                    }
                })
                .progress(new UpLoadCallback() {
                    @Override
                    public void onProgress(Object tag, int progress, long speed, boolean done) {
                        updateProgressDialog(progress);
                    }

                    @Override
                    public void onStart(Object tag) {
                        showPressDialog();
                    }
                })
                .build()
                .upload());
    }

    /**
     * 初始化进度条
     */
    private void initProgress(Context aContext) {

        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(aContext);
        }

        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setTitle("温馨提示");
        mProgressDialog.setMax(100);
        mProgressDialog.setMessage("正在上传中...");
        mProgressDialog.setCancelable(true);

    }

    private void updateProgressDialog(int progress) {

        if (mProgressDialog != null) {
            if (!mProgressDialog.isShowing()) {
                showPressDialog();
            }
            mProgressDialog.setProgress(progress);
        }
    }

    private void showPressDialog() {

        if (mProgressDialog == null || getActivity().isFinishing()) {
            return;
        }
        mProgressDialog.show();
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }
}
